package JDBC;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class insertSql {
    public static void main(String[] args) throws SQLException {
        //1创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/student?characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("");
        //2建立连接
        Connection connection = dataSource.getConnection();
        //3构造sql

        System.out.println("请输入学生的学号:");
        Scanner sc1 = new Scanner(System.in);
        int id = sc1.nextInt();
        System.out.println("请输入学生的姓名:");
        Scanner sc2 = new Scanner(System.in);
        String name = sc2.next();

        String sql = "insert into student values (?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);
        //4执行sql
        int n = statement.executeUpdate();
        System.out.println("n= "+n);
        //5释放资源
        statement.close();
        connection.close();
    }
}
